<template>
  <div class="app-container">
    <div class="m-header">
      <div>
        <in-line />
      </div>
      <div>
        <device />
      </div>
      <div>
        <type-num />
      </div>
    </div>

    <div v-permission="['machine:create']" class="addbtn" @click="dialogTop('add')">添加设备</div>
    <div class="seatch">
      <el-input
        v-model="listQuery.keyword"
        placeholder="按名称搜索"
        @keyup.enter.native="searchName($event)"
      >
        <i slot="prefix" class="el-input__icon el-icon-search" @click="getList()" />
      </el-input>
    </div>
    <div class="content">
      <el-table
        v-loading="listLoading"
        align="center"
        :data="tableData"
        style="width: 100%"
      >
        <el-table-column
          prop="name"
          align="center"
          label="设备名称"
        />
        <el-table-column
          prop="typeName"
          align="center"
          label="设备类型"
        />
        <el-table-column
          align="center"
          prop="num"
          label="设备编号"
        />
        <el-table-column
          align="center"
          prop="user"
          label="设备使用者"
        />
        <el-table-column
          align="center"
          prop="safer"
          label="安全员"
        />
        <el-table-column
          align="worker"
          prop="safer"
          label="安拆工"
        />
        <el-table-column
          align="center"
          prop="commander"
          label="指挥人员"
        >
          <!-- <template slot-scope="{row}">
            <div>{{ row.isMyself?'自己':'分包商' }}</div>
          </template> -->
        </el-table-column>
        <el-table-column
          align="center"
          prop="createAt"
          label="操作"
          width="220"
        >
          <template slot-scope="{row}">
            <div class="operate">
              <div @click="detailDialog(row)">详情</div>
              <div v-permission="['machine:edit']" @click="edgeDialog(row)">编辑</div>
              <div v-permission="['machine:delete']" @click="deleteDialog(row)">删除</div>
            </div>
          </template>
        </el-table-column>
      </el-table>
      <div class="pageination-div">
        <pagination v-show="total>0" :total="total" :page.sync="listQuery.pageNum" :limit.sync="listQuery.pageSize" @pagination="getList" />
      </div>
    </div>
    <!-- 添加,编辑 -->
    <el-dialog :title="diaDelOrAdd?'添加设备':'编辑设备'" :visible.sync="dialogFormVisible" :close-on-click-modal="false" width="55%">
      <el-form ref="addForm" :model="addForm" :rules="rules" auto-complete="on" label-position="left" style="width: 97%;">
        <el-form-item label="设备名称：" :label-width="formLabelWidth" prop="name">
          <el-input
            v-model="addForm.name"
            placeholder="请输入名称"
            name="name"
            maxlength="32"
            tabindex="1"
            autocomplete="off"
          />
        </el-form-item>
        <el-form-item label="设备类型：" prop="type" :label-width="formLabelWidth">
          <el-select v-model="addForm.type" placeholder="请选择">
            <el-option
              v-for="item in typeList"
              :key="item.id"
              :label="item.name"
              :value="item.id"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="设备编号：" :label-width="formLabelWidth" prop="num">
          <el-input
            v-model="addForm.num"
            placeholder="请输入设备编号"
            name="num"
            maxlength="32"
            tabindex="2"
            autocomplete="off"
          />
        </el-form-item>
        <el-form-item label="安装高度：" :label-width="formLabelWidth" prop="high">
          <el-input
            v-model="addForm.high"
            placeholder="请输入首次安装高度/最终安装高度"
            name="high"
            maxlength="32"
            tabindex="3"
            autocomplete="off"
          />
        </el-form-item>
        <el-form-item label="设备产权备案号：" :label-width="formLabelWidth" prop="propertyNo">
          <el-input
            v-model="addForm.propertyNo"
            placeholder="请输入设备产权备案号"
            name="propertyNo"
            maxlength="32"
            tabindex="4"
            autocomplete="off"
          />
        </el-form-item>
        <el-form-item label="使用登记编号：" :label-width="formLabelWidth" prop="useNo">
          <el-input
            v-model="addForm.useNo"
            placeholder="请输入使用登记编号"
            name="useNo"
            maxlength="32"
            tabindex="4"
            autocomplete="off"
          />
        </el-form-item>
        <el-form-item label="安装单位：" :label-width="formLabelWidth" prop="installUnit">
          <el-input
            v-model="addForm.installUnit"
            placeholder="请输入安装单位"
            name="installUnit"
            maxlength="32"
            tabindex="4"
            autocomplete="off"
          />
        </el-form-item>
        <el-form-item label="使用单位：" :label-width="formLabelWidth" prop="useUnit">
          <el-input
            v-model="addForm.useUnit"
            placeholder="请输入使用单位"
            name="useUnit"
            maxlength="32"
            tabindex="4"
            autocomplete="off"
          />
        </el-form-item>
        <el-form-item label="租赁单位：" :label-width="formLabelWidth" prop="leaseUnit">
          <el-input
            v-model="addForm.leaseUnit"
            placeholder="请输入租赁单位"
            name="leaseUnit"
            maxlength="32"
            tabindex="4"
            autocomplete="off"
          />
        </el-form-item>
        <el-form-item label="检测单位：" :label-width="formLabelWidth" prop="testUnit">
          <el-input
            v-model="addForm.testUnit"
            placeholder="请输入检测单位"
            name="testUnit"
            maxlength="32"
            tabindex="4"
            autocomplete="off"
          />
        </el-form-item>
        <el-form-item label="建设单位：" :label-width="formLabelWidth" prop="buildUnit">
          <el-input
            v-model="addForm.buildUnit"
            placeholder="请输入建设单位"
            name="buildUnit"
            maxlength="32"
            tabindex="4"
            autocomplete="off"
          />
        </el-form-item>
        <el-form-item label="监理单位：" :label-width="formLabelWidth" prop="supervisorUnit">
          <el-input
            v-model="addForm.supervisorUnit"
            placeholder="请输入监理单位"
            name="supervisorUnit"
            maxlength="32"
            tabindex="4"
            autocomplete="off"
          />
        </el-form-item>
        <!-- <el-form-item label="入场日期：" :label-width="formLabelWidth" prop="dataTime">
          <div class="block">
            <el-date-picker
              v-model="addForm.dataTime"
              value-format="yyyy-MM-dd"
              type="daterange"
              align="right"
              unlink-panels
              range-separator="至"
              start-placeholder="入场时间"
              end-placeholder="离场时间"
            />
          </div>
        </el-form-item> -->
        <el-form-item label="设备使用者：" :label-width="formLabelWidth" prop="user">
          <el-input
            v-model="addForm.user"
            placeholder="请输入(姓名+执照证件号)"
            name="user"
            maxlength="32"
            tabindex="3"
            autocomplete="off"
          />
        </el-form-item>
        <el-form-item label="指挥人员：" :label-width="formLabelWidth" prop="commander">
          <el-input
            v-model="addForm.commander"
            placeholder="请输入(姓名+执照证件号)"
            name="commander"
            maxlength="32"
            tabindex="3"
            autocomplete="off"
          />
        </el-form-item>
        <el-form-item label="安拆工：" :label-width="formLabelWidth" prop="worker">
          <el-input
            v-model="addForm.worker"
            placeholder="请输入(姓名+执照证件号)"
            name="worker"
            maxlength="32"
            tabindex="3"
            autocomplete="off"
          />
        </el-form-item>
        <el-form-item label="专职设备管理员：" :label-width="formLabelWidth" prop="manager">
          <el-input
            v-model="addForm.manager"
            placeholder="请输入专职设备管理员"
            name="manager"
            maxlength="32"
            tabindex="3"
            autocomplete="off"
          />
        </el-form-item>
        <el-form-item label="专职安全员：" :label-width="formLabelWidth" prop="safer">
          <el-input
            v-model="addForm.safer"
            placeholder="请输入专职安全员"
            name="safer"
            maxlength="32"
            tabindex="3"
            autocomplete="off"
          />
        </el-form-item>
        <div class="tab" style="width:105%;">
          <div class="imgtitle">
            <label>上传照片：</label>
            <div style="margin: 20px 0 0 0;">
              <el-form-item>
                <el-upload
                  ref="upload"
                  :action="pathUrl+'/file/img'"
                  list-type="picture-card"
                  :on-preview="handlePictureCardPreview"
                  :on-remove="handleRemove"
                  :on-success="handleAvatarSuccess"
                  :before-upload="beforeAvatarUpload"
                >
                  <i class="el-icon-plus" />
                </el-upload>
                <div v-if="diaDelOrAdd">
                  <el-dialog :visible.sync="dialogVisible">
                    <img width="100%" :src="dialogImageUrl" alt="">
                  </el-dialog>
                </div>
                <div v-else>
                  <div class="tab">
                    <div class="row">
                      <div v-if="addForm.linaFiles" class="imgtext" style="margin-left: 33px;">历史照片：</div>
                      <div v-for="(img, key) in addForm.linaFiles" :key="key" class="imgList">
                        <div>
                          <img
                            style="width:150px;height:100px;margin: 0 0 5px 10px;"
                            :src="img.path"
                            :alt="img.name"
                          >
                          <i
                            class="el-icon-delete"
                            style="position: absolute;
                                  margin: -10% 0 0 9%;"
                            @click="deleteImg(img.id)"
                          />
                        </div>
                      </div>
                    </div>
                  </div>
                </div>
              </el-form-item>
            </div>
          </div>
        </div>
      </el-form>
      <div class="footer">
        <div class="cancel" @click="dialogTop('cancel')">
          <span>取消</span>
        </div>
        <div v-if="diaDelOrAdd" class="sure" @click="createData">
          <span>确认</span>
        </div>
        <div v-else class="sure" @click="updataData">
          <span>确认</span>
        </div>
      </div>
    </el-dialog>

    <!-- 详情 -->
    <el-dialog title="设备详情" :visible.sync="detailDialogVisible" :close-on-click-modal="false" custom-class="55%;">
      <el-form label-position="left" style="width: 97%;">
        <el-form-item label="设备名称：" :label-width="formLabelWidth">
          <div class="textName"><span>{{ detailData.name }}</span></div>
        </el-form-item>
        <el-form-item label="设备类型：" prop="type" :label-width="formLabelWidth">
          <div class="textName"><span>{{ detailData.typeName }}</span></div>
        </el-form-item>
        <el-form-item label="设备编号：" :label-width="formLabelWidth">
          <div class="textName"><span>{{ detailData.num }}</span></div>
        </el-form-item>
        <el-form-item label="安装高度：" :label-width="formLabelWidth">
          <div class="textName"><span>{{ detailData.high }}</span></div>
        </el-form-item>
        <el-form-item label="设备产权备案号：" :label-width="formLabelWidth">
          <div class="textName"><span>{{ detailData.propertyNo }}</span></div>
        </el-form-item>
        <el-form-item label="使用登记编号：" :label-width="formLabelWidth">
          <div class="textName"><span>{{ detailData.useNo }}</span></div>
        </el-form-item>
        <el-form-item label="安装单位：" :label-width="formLabelWidth">
          <div class="textName"><span>{{ detailData.installUnit }}</span></div>
        </el-form-item>
        <el-form-item label="使用单位：" :label-width="formLabelWidth">
          <div class="textName"><span>{{ detailData.useUnit }}</span></div>
        </el-form-item>
        <el-form-item label="租赁单位：" :label-width="formLabelWidth">
          <div class="textName"><span>{{ detailData.leaseUnit }}</span></div>
        </el-form-item>
        <el-form-item label="检测单位：" :label-width="formLabelWidth">
          <div class="textName"><span>{{ detailData.testUnit }}</span></div>
        </el-form-item>
        <el-form-item label="建设单位：" :label-width="formLabelWidth">
          <div class="textName"><span>{{ detailData.buildUnit }}</span></div>
        </el-form-item>
        <el-form-item label="监理单位：" :label-width="formLabelWidth">
          <div class="textName"><span>{{ detailData.supervisorUnit }}</span></div>
        </el-form-item>
        <el-form-item label="设备使用者：" :label-width="formLabelWidth">
          <div class="textName"><span>{{ detailData.user }}</span></div>
        </el-form-item>
        <el-form-item label="指挥人员：" :label-width="formLabelWidth">
          <div class="textName"><span>{{ detailData.commander }}</span></div>
        </el-form-item>
        <el-form-item label="安拆工：" :label-width="formLabelWidth">
          <div class="textName"><span>{{ detailData.worker }}</span></div>
        </el-form-item>
        <el-form-item label="专职设备管理员：" :label-width="formLabelWidth">
          <div class="textName"><span>{{ detailData.manager }}</span></div>
        </el-form-item>
        <el-form-item label="专职安全员：" :label-width="formLabelWidth">
          <div class="textName"><span>{{ detailData.safer }}</span></div>
        </el-form-item>
        <el-form-item>
          <div class="tab">
            <div class="row">
              <div class="imgtext" style="margin-left: 86px;">照片：</div>
              <div v-for="(img, key) in detailData.linaFiles" :key="key" class="imgList">
                <div>
                  <img style="width:150px;height:100px;margin: 0 0 5px 10px;" :src="img.path" :alt="img.name">
                </div>
              </div>
            </div>
          </div>
        </el-form-item>
      </el-form>
      <div class="footer">
        <div class="cancel" @click="cancelClear()">
          <span>取消</span>
        </div>
      </div>
    </el-dialog>

    <delete-dialog
      :dislog-name="deleteObiect.name"
      :dialog-del-visible="dialogDelVisible"
      :title="'设备'"
      @funcancl="funcancl"
      @func="deleteData"
    />

  </div>
</template>

<script>
import Pagination from '@/components/pagination'
import DeleteDialog from '@/components/dialog/delete'
import { deleteFiles } from '@/api/file'
import InLine from './components/inLine'
import Device from './components/device'
import TypeNum from './components/typeNum'
import { machineList, createMachine, updataMachine, deleteMachine, detailMachine, getMachineType } from '@/api/machine'
export default {
  name: 'Equipment',
  components: {
    Pagination,
    DeleteDialog,
    InLine,
    Device,
    TypeNum
  },
  data() {
    return {
      pathUrl: process.env.VUE_APP_BASE_API,
      tableData: [],
      detailData: {},
      total: 0,
      listLoading: true,
      listQuery: {
        keyword: null,
        pageNum: 1,
        pageSize: 10
      },
      dialogFormVisible: false,
      dialogDelVisible: false,
      formLabelWidth: '140px',
      lablePosition: 'left',
      diaDelOrAdd: false,
      detailDialogVisible: false,
      dialogImageUrl: '',
      dialogVisible: false,
      addForm: {
        name: '',
        type: '',
        num: '',
        high: '',
        propertyNo: '',
        useNo: '',
        installUnit: '',
        useUnit: '',
        leaseUnit: '',
        testUnit: '',
        buildUnit: '',
        supervisorUnit: '',
        user: '',
        commander: '',
        worker: '',
        manager: '',
        safer: '',
        linaFiles: []
        // dataTime: []
      },
      deleteObiect: {},
      typeList: [],
      imagerType: ['image/jpeg', 'image/gif', 'image/bmp', 'image/png', 'image/jpg'],
      rules: {
        name: [
          { required: true, message: '必填', trigger: 'change' }
        ],
        type: [
          { required: true, message: '必填', trigger: 'change' }
        ],
        num: [
          { required: true, message: '必填', trigger: 'change' }
        ]
        // dataTime: [
        //   { required: true, message: '必填', trigger: 'change' }
        // ],
        // high: [
        //   { required: true, message: '必填', trigger: 'change' },
        //   //  { pattern: /(^[1-9]{1}[0-9]*$)|(^[0-9]*\.[0-9]{2}$)/, message: '只能输入数字或者数字加小数点后两位' }
        // ],
        // propertyNo: [
        //   { required: true, message: '必填', trigger: 'change' }
        // ],
        // useNo: [
        //   { required: true, message: '必填', trigger: 'change' }
        // ],
        // installUnit: [
        //   { required: true, message: '必填', trigger: 'change' }
        // ],
        // useUnit: [
        //   { required: true, message: '必填', trigger: 'change' }
        // ],
        // leaseUnit: [
        //   { required: true, message: '必填', trigger: 'change' }
        // ],
        // testUnit: [
        //   { required: true, message: '必填', trigger: 'change' }
        // ],
        // buildUnit: [
        //   { required: true, message: '必填', trigger: 'change' }
        // ],
        // supervisorUnit: [
        //   { required: true, message: '必填', trigger: 'change' }
        // ],
        // user: [
        //   { required: true, message: '必填', trigger: 'change' }
        // ],
        // commander: [
        //   { required: true, message: '必填', trigger: 'change' }
        // ],
        // worker: [
        //   { required: true, message: '必填', trigger: 'change' }
        // ],
        // manager: [
        //   { required: true, message: '必填', trigger: 'change' }
        // ],
        // safer: [
        //   { required: true, message: '必填', trigger: 'change' }
        // ],
      }
    }
  },
  computed: {

  },
  mounted() {
    this.getList()
    this.machineType()
  },
  methods: {
    sizeChange(val) {
      this.pageNum = val
    },
    currentChange(val) {
      this.currentPage = val
    },
    searchName(e) {
      this.listQuery.keyword = e.target.value
      this.getList()
    },
    clean() {
      this.addForm = {
        name: '',
        type: '',
        num: '',
        entryDate: '',
        outDate: '',
        high: '',
        propertyNo: '',
        useNo: '',
        installUnit: '',
        useUnit: '',
        leaseUnit: '',
        testUnit: '',
        buildUnit: '',
        supervisorUnit: '',
        user: '',
        commander: '',
        worker: '',
        manager: '',
        safer: '',
        linaFiles: []

      }
      this.dialogImageUrl = ''
    },
    cancelClear() {
      this.detailDialogVisible = false
      this.$nextTick(() => {
        this.$refs.upload.clearFiles()
      })
      this.clean()
    },
    funcancl(val) {
      this.dialogDelVisible = false
    },
    funsetcancl(val) {
      this.dialogResetVisible = false
    },
    // 获取数据
    async getList() {
      const res = await machineList(this.listQuery)
      if (res.code === 200) {
        this.tableData = res.data.list
        this.total = res.data.total || 0
        this.pages = res.data.pages || 0
        this.listLoading = false
      }
    },
    // 获取设备类型
    async machineType() {
      const res = await getMachineType()
      if (res.code === 200) {
        this.typeList = res.data
      }
    },
    dialogTop(val, row) {
      if (val === 'cancel') {
        this.diaDelOrAdd = false
        this.dialogFormVisible = false
      } else {
        this.diaDelOrAdd = true
        this.dialogFormVisible = true
      }
      this.clean()
      this.$nextTick(() => {
        this.$refs.addForm.clearValidate()
      })
    },
    edgeDialog(row) {
      this.diaDelOrAdd = false
      this.dialogFormVisible = true
      this.addForm = {
        id: row.id,
        name: row.name,
        type: row.type,
        num: row.num,
        high: row.high,
        propertyNo: row.propertyNo,
        useNo: row.useNo,
        installUnit: row.installUnit,
        useUnit: row.useUnit,
        leaseUnit: row.leaseUnit,
        testUnit: row.testUnit,
        buildUnit: row.buildUnit,
        supervisorUnit: row.supervisorUnit,
        user: row.user,
        commander: row.commander,
        worker: row.worker,
        manager: row.manager,
        safer: row.safer,
        linaFiles: row.linaFiles
      }
      this.$nextTick(() => {
        this.$refs.addForm.clearValidate()
        this.$refs.upload.clearFiles()
      })
    },
    createData() {
      this.$refs.addForm.validate(async valid => {
        if (valid) {
          const res = await createMachine(this.addForm)
          if (res.code === 200) {
            this.dialogFormVisible = false
            this.clean()
            this.$message({
              type: 'success',
              message: '创建成功!',
              showClose: true,
              center: true,
              duration: 2 * 1000
            })
            this.getList()
          } else {
            console.log(res)
          }
        }
      })
    },
    updataData() {
      this.$refs.addForm.validate(async valid => {
        if (valid) {
          const res = await updataMachine(this.addForm)
          if (res.code === 200) {
            this.dialogFormVisible = false
            this.$message({
              type: 'success',
              message: '编辑成功!',
              showClose: true,
              center: true,
              duration: 2 * 1000
            })
            this.getList()
          } else {
            this.dialogFormVisible = false
          }
        }
      })
    },
    // 删除
    deleteDialog(row) {
      this.dialogDelVisible = true
      this.deleteObiect = row
    },
    async deleteData() {
      const id = this.deleteObiect.id
      const res = await deleteMachine(id)
      if (res.code === 200) {
        this.getList()
        this.dialogDelVisible = false
        this.$message({
          type: 'success',
          message: '删除成功!',
          showClose: true,
          center: true,
          duration: 2 * 1000
        })
      } else {
        this.dialogDelVisible = false
      }
    },
    async detailDialog(row) {
      this.detailDialogVisible = true
      const id = row.id
      const res = await detailMachine(id)
      if (res.code === 200) {
        this.detailData = res.data
        if (this.detailData) {
          for (let i = 0; i < this.typeList.length; i++) {
            if (this.typeList[i].id === this.detailData.id) {
              this.detailData.typeName = this.typeList[i].name
            }
          }
        }
      } else {
        console.log(res)
      }
    },
    // 图片上传
    handleAvatarSuccess(res, file, fileList) {
      if (res.code === 200) {
        this.addForm.linaFiles.push(res.data)
        this.$message({
          type: 'success',
          message: '图片上传成功!',
          showClose: true,
          center: true,
          duration: 2 * 1000
        })
      } else {
        this.$refs.upload.clearFiles()
        this.$message({
          type: 'error',
          message: res.msg || 'error',
          showClose: true,
          center: true,
          duration: 2 * 1000
        })
      }
    },
    beforeAvatarUpload(file) {
      // eslint-disable-next-line no-unneeded-ternary
      const isJPG = this.imagerType.indexOf(file.type) !== -1
      const isLt10M = file.size / 1024 / 1024 < 10
      if (!isJPG) {
        this.$message({
          type: 'error',
          message: '上传头像图片只能是 JPG,JPEG,PNG,GIF 格式!',
          showClose: true,
          center: true,
          duration: 2 * 1000
        })
      }
      if (!isLt10M) {
        this.$message({
          type: 'error',
          message: '上传图片大小不能超过 10MB!',
          showClose: true,
          center: true,
          duration: 2 * 1000
        })
      }
      return isJPG && isLt10M
    },
    async handleRemove(file, fileList) {
      const id = file.response.data.id
      const res = await deleteFiles(id)
      if (res.code === 200) {
        this.addForm.linaFiles.splice(this.addForm.linaFiles.findIndex(item => item.id === id), 1)
        this.$message({
          type: 'success',
          message: '图片删除成功!',
          showClose: true,
          center: true,
          duration: 2 * 1000
        })
      } else {
        console.log('图片删除失败!')
      }
      // console.log(file, fileList)
    },
    handlePictureCardPreview(file) {
      this.dialogImageUrl = file.url
      this.dialogVisible = true
    },
    async deleteImg(id) {
      const res = await deleteFiles(id)
      if (res.code === 200) {
        this.addForm.linaFiles.splice(this.addForm.linaFiles.findIndex(item => item.id === id), 1)
        this.$message({
          type: 'success',
          message: '图片删除成功!',
          showClose: true,
          center: true,
          duration: 2 * 1000
        })
      } else {
        console.log('图片删除失败!')
      }
      // console.log(file, fileList)
    }
  }
}
</script>
<style lang="scss" scoped>
.app-container{
   .m-header{
    display: flex;
    margin: 21px 18px 0 18px;
    div{
        width:100%;
        background:rgba(37,38,47,1);
        margin-right: 15px;
      }
  }
  .textName{
    font-size:14px;
    font-weight:400;
    color:rgba(247,181,0,0.8);
    span{
      font-size:14px;
      font-weight:400;
      color:rgba(255,255,255,0.8);
    }
  }
}
.imgtitle{
    font-size: 14px;
    font-weight: 400;
    color: rgba(247,181,0,.8);
    label{
      margin-left: 56px;
      font-weight: 400 !important;
    }
  }
  .imgtext{
    font-size: 14px;
    font-weight: 400;
    color: rgba(247,181,0,.8);
    margin: 0 0 20px 0;
  }
  .imgList{
    cursor: pointer;
    width: 150px;
    float: left;
    margin-right: 20px;
    div{
       margin-left: 10px;
    }
  }
</style>
